<template>
    <div class="main">
        <div ref="toolbar">
            <ToolbarPanel/>
        </div>
        <div ref="itemPanel" class="item-panel">
            <ItemPanel/>
        </div>
        <div ref="canvas" class="canvas-panel"></div>
        <DetailPanel :detailGraph="detailGraph" @change="change"/>
        <div class="clear"></div>
    </div>
</template>
<script>
    import ToolbarPanel from "@/components/ToolbarPanel/index.vue";
    import ItemPanel from "@/components/ItemPanel/index.vue";
    import DetailPanel from "@/components/DetailPanel/index.vue";
    import AddItemPanel from "@/draw/plugins/addItemPanel";
    import CanvasPanel from "@/draw/plugins/canvasPanel";
    import Command from "@/draw/plugins/command";
    import Toolbar from "@/draw/plugins/toolbar";
    import G6 from "@antv/g6/lib"
    import registerShape from "@/draw/shape/index";
    import registerBehavior from "@/draw/behavior/index";

    registerShape(G6);
    registerBehavior(G6);
    import {Dictionary} from "../../utils/Dictionary";
    import {listByTypes} from "../../api/dictionary";
    import {details} from "../../api/map"
    import {Base64} from 'js-base64';
    export default {
        name: 'drawMap',
        data() {
            return {
                graph: null,
                pageRef: null,
                itemPanelRef: null,
                toolbar: null,
                cmdPlugin: null,
                resizeFunc: () => {
                },
                detailGraph: {},
                id: '',
                map: {},
                nodes: [
                ],
                edges:[
                ]
            }
        },
        components: {
            ToolbarPanel,
            ItemPanel,
            DetailPanel
        },
        mounted() {
            this.pageRef = this.$refs.canvas;
            this.itemPanelRef = this.$refs.itemPanel;
            this.toolbar = this.$refs.toolbar;
            this._loadDictionary();
            const query = this.$route.query;
            Object.keys(query).length > 0 ? this._details(query) : this.componentDidMount();
        },
        methods: {

            /**
             *
             * 查询详细
             */
            _details(query){
                this.id = JSON.parse(Base64.decode(Object.keys(query).map(item => query[item]).join(""))).id;
                details(this.id).then(res => {
                        const data = res.data;
                    this.map = {id: this.id, name: data.name, type: data.type, remark: data.remark};
                    const width = 4017;
                    const height = 5244;
                    const model = {id: '1',size:[width, height], clazz: 'map', type: 'map-node', x: -width/2, y: -height/2, src: data.path};
                    // let pointX = 246.106934/0.08 - (width/2);
                    // let pointY = (height/2)-(53.840420/0.08);
                    this.nodes = [model, ...data.nodes?.map(item => {
                        const size = item.size?.split(",");
                        return {...item,id: item.uuid, size: size && [parseInt(size[0]), parseInt(size[1])]}
                    })]; 
                    this.componentDidMount();
                    // this.edges = data.edges?.map(item => {
                    //     return {...item,
                    //         controlPoints: JSON.parse(item.controlPoints),
                    //         startPoint: JSON.parse(item.startPoint),
                    //         endPoint: JSON.parse(item.startPoint),
                    //         isDash: item.isDash == '1' ? true : false,
                    //         isArrow: item.isArrow == '1' ? true : false,
                    //         id: item.uuid,
                    //         style: {},
                    //         shiftKey: true,
                    //     }
                    // });
                  
                })
            },

            /**
             *
             * 加载字典
             * @private
             */
            _loadDictionary(){
                listByTypes(Object.keys(Dictionary).map(item => item).join(",")).then(res => {
                    this.$store.commit('setDictionary', res.data);
                })
            },

            componentDidMount() {
                this.cmdPlugin = new Command();
                const addItemPanel = new AddItemPanel({container: this.itemPanelRef});
                const canvasPanel = new CanvasPanel({container: this.pageRef});
                const toolbar = new Toolbar({container: this.toolbar});
                let plugins = [this.cmdPlugin, toolbar, addItemPanel, canvasPanel];
                this.graph = new G6.Graph({
                    plugins: plugins,
                    container: this.pageRef,
                    rotating: true,
                    modes: {
                        default: ['drag-canvas', 'clickSelected'],
                        view: [],
                        edit: ['drag-canvas', 'dragNode', 'clickSelected', 'dragPanelItemAddNode', 'itemAlign', 'dragAnchor']
                    },
                });
                const nodes = this.nodes;
                this.graph.map = this.map;
                this.graph.setMode("edit");
                this.graph.data({nodes: nodes, edges: this.edges});
                this.graph.render();
                this.initEvents();
            },

            initEvents() {
                this.graph.on('afteritemselected', items => {
                    // console.log(items);
                    if (items && items.length > 0) {
                        let item = this.graph.findById(items[0]);
                        // console.log(item.getModel().clazz);
                        this.detailGraph = {graph: this.graph, itemId: items[0], clazz: item.getModel().clazz}
                    } else {
                        this.detailGraph = {graph: this.graph, itemId: null, clazz: 'canvas'}
                    }
                });
                this.graph.on('click', (e) => {
                    const item = e.item;
                    if (!item) {
                        this.graph.emit('canvas:click', e);
                    }
                });
                this.graph.on('wheel', (e) => {
                    const maxZoom = graph.get('maxZoom');
                    const zoom = graph.getZoom();
                    let currentZoom = zoom
                    if(e.deltaY < 0){
                       // 向下滚动
                        currentZoom = zoom - 0.1;
                    }else{
                        // 向上滚动
                        currentZoom = zoom + 0.1;
                    }
                    if(currentZoom > maxZoom){
                        currentZoom = maxZoom;
                    }
                    graph.zoomTo(currentZoom);
                });
                this.graph.on('afterdelete', (e) => {
                    this.graph.set("selectedItems", []);
                    this.graph.emit('afteritemselected', e);
                })
                const page = this.pageRef;
                const graph = this.graph;
                this.resizeFunc = () => {
                    graph.changeSize(page.offsetWidth, page.offsetHeight);
                }
                window.addEventListener("resize", this.resizeFunc);
            },

            change(param) {
                const items = this.graph.get("selectedItems");
                if (items && items.length > 0) {
                    if(this.graph.executeCommand){
                        this.graph.executeCommand('update', {
                            itemId: items[0],
                            updateModel: {...param},
                        })
                    }
                }
            }
        }
    }
</script>

<style lang="scss">
    @import "./index.scss";
</style>
